package com.quasar.hpatient.view.doctor;

import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.Aerainfodb;
import com.quasar.hpatient.model.litePalmodel.DepartMentInfodb;
import com.quasar.hpatient.model.litePalmodel.HospitalInfodb;
import com.quasar.hpatient.model.medicalmodel.DoctorListBean;
import com.quasar.hpatient.onInterface.OnDoctorListener;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.DoctorFindPresenter;
import com.quasar.hpatient.presenter.UpdateDoctorPatientPresenter;
import com.quasar.hpatient.view.adapter.DoctorFindAdapter;
import com.quasar.hpatient.widget.SideBarView;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 医生库
 */
@EActivity(R.layout.activity_doctor_find)
public class DoctorFindActivity extends BaseActivity implements OnDoctorListener {

    public DoctorFindAdapter doctorFindAdapter;

    private DoctorFindPresenter doctorFindPresenter;

    //获取地理信息
    List<Aerainfodb> Geography = new ArrayList<>();
    int keshi;
    String rName = "";
    /**
     * 医院筛选
     */
    List<HospitalInfodb> hospitalInfoDBList = MainAppliaction.getInstance().getHospitalInfodbList();
    private List<List<HospitalInfodb>> screenHospitalList = new ArrayList<>();
    int hospital;
    /**
     * 选择科室
     */
    List<DepartMentInfodb> departMentInfoDBList = MainAppliaction.getInstance().getDepartMentInfoList();
    private List<DepartMentInfodb> options1departMentInfo = new ArrayList<>();
    private List<List<DepartMentInfodb>> options2departMentInfo = new ArrayList<>();

    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.ll_search)
    LinearLayout ll_search;
    @ViewById(R.id.et_search)
    EditText et_search;
    @ViewById(R.id.side_bar)
    SideBarView side_bar;

    @AfterViews
    void init() {
        initView();
        initData();

    }

    boolean isClick=true;
    //初始化adapter布局
    public void initAdapter() {
        doctorFindAdapter = new DoctorFindAdapter();
        rv_list.setAdapter(doctorFindAdapter);
        //初始化数据
        doctorFindPresenter.StarDoctorList("");
        //item点击

        doctorFindAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {

                switch (view.getId()) {
                    case R.id.tv_apply://申请

                        if (doctorFindAdapter.getData().get(position).getDoctorPatientRelative() != null) {

                            DoctorListBean doctorListBean=doctorFindAdapter.getData().get(position);
                            //删除医生
                            if( doctorListBean.getDoctorPatientRelative().getRelationType()== ConstantManger.Relation2
                                || doctorListBean.getDoctorPatientRelative().getRelationType()==ConstantManger.Relation4
                                || doctorListBean.getDoctorPatientRelative().getRelationType()==ConstantManger.Relation10
                                || doctorListBean.getDoctorPatientRelative().getRelationType()==ConstantManger.Relation20
                                || doctorListBean.getDoctorPatientRelative().getRelationType()==ConstantManger.stopRelation
                                || doctorListBean.getDoctorPatientRelative().getRelationType()==ConstantManger.Relation1){

                                if(isClick){
                                    doctorFindPresenter.DeletePatientData(doctorFindAdapter.getData().get(position).getId() + "");
                                }
                                isClick=false;
                             }else{
                                //申请医生
                                if(isClick){
                                    doctorFindPresenter.PostUpdateDoctorPatient(doctorFindAdapter.getData().get(position).getId() + "");
                                }
                                isClick=false;

                            }
                        }

                        break;
                    case R.id.headimg://进入医生详情界面
                        DoctorDetailsActivity_.intent(DoctorFindActivity.this).doctor(doctorFindAdapter.getItem(position)).start();
                        break;
                }
            }
        });


    }

    @Override
    protected void initView() {
        initToolbar();
        initSearchEdittext();
        rv_list.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void initData() {
        doctorFindPresenter = new DoctorFindPresenter(this);
        initAdapter();
    }

//     tv_department.setText("科室选择");
//        tv_hospital.setText("医院选择");
//        et_search.setText("");


    //获取热门医生
    @Override
    public void onDoctorListSuccess(final AnotherResult<DoctorListBean> data) {
        //按照字母排序
        Collections.sort(data.getList(), new Comparator<DoctorListBean>() {
            @Override
            public int compare(DoctorListBean o1, DoctorListBean o2) {
                if (o2.getIndex().equals("#")) {
                    return -1;
                } else if (o1.getIndex().equals("#")) {
                    return 1;
                } else {
                    return o1.getIndex().compareTo(o2.getIndex());
                }
            }
        });
        doctorFindAdapter.setNewData(data.getList());
        side_bar.setOnSelectIndexItemListener(new SideBarView.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                for (int i = 0; i < data.getList().size(); i++) {
                    if (data.getList().get(i).getIndex().equals(index)) {
                        ((LinearLayoutManager) rv_list.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });

    }

    @Override
    public void onMyDoctorSuccess(AnotherResult<DoctorListBean> data) {

    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
            isClick=true;
        }
    }

    @Override
    public void onRefreshUI() {
        doctorFindAdapter.notifyDataSetChanged();
    }




    @ViewById(R.id.tv_hospital)
    TextView tv_hospital;


    //选择科室
    @ViewById(R.id.tv_department)
    TextView tv_department;

    @Click(R.id.tv_department)
    public void tv_department() {
        Department();
    }

    public void Department() {
        options1departMentInfo.clear();
        options1departMentInfo = ListDepartment(0);
        for (int i = 0; i < options1departMentInfo.size(); i++) {
            List<DepartMentInfodb> options3departMentInfo = ListDepartment(options1departMentInfo.get(i).getPrimaryid());
            options2departMentInfo.add(options3departMentInfo);
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                //返回的分别是三个级别的选中位置
                String tx = options2departMentInfo.get(options1).get(options2).getPickerViewText();
                tv_department.setText(tx);
                //传入医院id,若医院ID不为空则传入
                String hospitalID;
                if (hospital == 0) {
                    hospitalID = "";
                } else {
                    hospitalID = hospital + "";
                }

                keshi = options2departMentInfo.get(options1).get(options2).getPrimaryid();
                doctorFindPresenter.PostMyDoctors("", "", hospitalID + "", options2departMentInfo.get(options1).get(options2).getPrimaryid() + "", "", rName);


            }
        })
                .setTitleText("科室选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1departMentInfo, options2departMentInfo);//二级选择器*/
        pvOptions.show();
    }

    public List<DepartMentInfodb> ListDepartment(int pid) {
        ArrayList<DepartMentInfodb> options1 = new ArrayList<>();
        int num = departMentInfoDBList.size();
        for (int i = 0; i < num; i++) {
            if (departMentInfoDBList.get(i).getPid() == pid) {
                options1.add(departMentInfoDBList.get(i));
            }
        }

        return options1;
    }

    //选择医院
    @Click(R.id.tv_hospital)
    public void tv_hospital() {
        ShowPickerView();
    }

    //根据省市信息获取医院
    public void screenHospital() {
        Geography.clear();
        Geography.addAll(MainAppliaction.getInstance().Geography());
        int num = Geography.size();
        int size = hospitalInfoDBList.size();
        for (int i = 0; i < num; i++) {
            ArrayList<HospitalInfodb> options1 = new ArrayList<>();
            for (int z = 0; z < size; z++) {

                if (Geography.get(i).getPrimary() == hospitalInfoDBList.get(z).getProvinceID()) {
                    options1.add(hospitalInfoDBList.get(z));
                }
            }
            screenHospitalList.add(options1);
        }
    }


    private void ShowPickerView() {// 弹出选择器
        screenHospital();
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = screenHospitalList.get(options1).get(options2).getPickerViewText();
                tv_hospital.setText(tx);
                Toast.makeText(DoctorFindActivity.this, tx, Toast.LENGTH_SHORT).show();

                hospital = screenHospitalList.get(options1).get(options2).getPrimaryid();

                //获取科室id,如果科室id不为空则传入
                String bumen;
                if (keshi == 0) {
                    bumen = "";
                } else {
                    bumen = keshi + "";
                }
                doctorFindPresenter.PostMyDoctors("", "", hospital + "", bumen + "", "", rName);
            }
        })

                .setTitleText("医院选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(Geography, screenHospitalList);//三级选择器  ,screenHospitalList
        pvOptions.show();
    }

    //搜索医生
    @Override
    public void onSubmitSuccess(final AnotherResult<DoctorListBean> dataStateResult) {

        //按照字母排序
        Collections.sort(dataStateResult.getList(), new Comparator<DoctorListBean>() {
            @Override
            public int compare(DoctorListBean o1, DoctorListBean o2) {
                if (o2.getIndex().equals("#")) {
                    return -1;
                } else if (o1.getIndex().equals("#")) {
                    return 1;
                } else {
                    return o1.getIndex().compareTo(o2.getIndex());
                }
            }
        });

        //判断page是否是下拉还是上拉
        doctorFindAdapter.setNewData(dataStateResult.getList());
        side_bar.setOnSelectIndexItemListener(new SideBarView.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                for (int i = 0; i < dataStateResult.getList().size(); i++) {
                    if (dataStateResult.getList().get(i).getIndex().equals(index)) {
                        ((LinearLayoutManager) rv_list.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });
    }

    //初始化搜索按钮
    public void initSearchEdittext() {
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String phone = et_search.getText().toString();
                    tv_department.setText("科室选择");
                    tv_hospital.setText("医院选择");
//                    selectFriendPresenter.PostAddFriend(phone);
                    rName = phone;
                    doctorFindPresenter.PostMyDoctors("", "", "", "", "", phone);
                    return false;
                }

                return false;
            }
        });
    }

    //删除医生
    @Override
    public void onDeleteDoctorx(DataStateResult dataStateResult) {
        if(dataStateResult.getMsgCode().equals("0x00000000")){
            msg("操作成功");
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.MYDOCTORX;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
    }

    //申请医生
    @Override
    public void onApplyDoctorx(DataStateResult dataStateResult) {
        if(dataStateResult.getMsgCode().equals("0x00000000")){
            msg("操作成功");
            isClick=true;
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.MYDOCTORX;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
    }

}
